﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using Maticsoft.DAL;
using System.Reflection;
using System.IO;
using Commons.CommonHelper;

namespace BuildingForm
{
    public partial class WorkHoursForm : Form,IModuleExtension 
    {
        public WorkHoursForm()
        {
            InitializeComponent();
            Init();
            bind();
        }
        
        private void Init()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            //表头加粗，居中
            foreach (DataGridViewColumn col in this.dataGridView1.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("SimSun", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.dataGridView1.AllowUserToAddRows = false;
            this.picBegin.Value = DateTime.Now;
            this.picEnd.Value = DateTime.Now;
            Maticsoft.DAL.Banz_Info info = new Banz_Info();
            DataTable dt = info.GetList("").Tables[0];
            List<string> strList = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strList.Add(dt.Rows[i]["bzmc"].ToString().Trim());
            }
            List<string> list = new List<string>();
            list.Add("全部");
            list.AddRange(strList);
            this.cboTeam.DataSource = list;
            
        }
        public decimal TotalHours = 0;
        private List<WorkTime> bind()
        {
            TotalHours = 0;
            Maticsoft.DAL.Kqjl_Info info = new Kqjl_Info();
            string sql = string.Empty;
            DateTime beginT = Convert.ToDateTime(picBegin.Value);
            DateTime endT = Convert.ToDateTime(picEnd.Value);
            if (beginT > endT)
            {
                MessageBox.Show("开始时间不能大于结束时间！"); return new List<WorkTime>();
            }
            sql = "CONVERT(varchar(10),a.kqsj,120)<='" + endT.ToString("yyyy-MM-dd") + "' and CONVERT(varchar(10),a.kqsj,120)>='" + beginT.ToString("yyyy-MM-dd") + "'";
            string team = this.cboTeam.Text.ToString().Trim();
            if (team != "全部")
            {
                sql += " and c.bzmc='" + team + "'";
            }
            sql += " order by a.sfzh,a.kqsj";
            DataTable dt = info.GetList2(sql).Tables[0];
            List<WorkTime> list = new List<WorkTime>();
            string sfzh_b = string.Empty;
            string dksj_b = string.Empty;
            DateTime beginTime = DateTime.MinValue;
            DateTime endTime = DateTime.MinValue;
            WorkTime arg = new WorkTime();
            int num=1; 
            decimal worktime = 0;
            //true进 false出
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string sfzh_1 = dr["sfzh"].ToString();
                string dksj_1 = dr["dksj"].ToString();
                //if (sfzh_1 != "0566805022") continue;
                if (sfzh_b.Equals(sfzh_1) && dksj_b.Equals(dksj_1))
                {
                    bool isEnter=Convert.ToBoolean (dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }
                    else
                    {
                        if (endTime == DateTime.MinValue&&beginTime!=DateTime.MinValue)
                        {
                            endTime = Convert.ToDateTime(dr["kqsj"]);
                            TimeSpan ts = endTime - beginTime;
                            decimal di=ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
                            worktime += di;
                            //防止一个人一天的再次
                            beginTime = DateTime.MinValue;
                            endTime = DateTime.MinValue;
                        }
                    }
                     
                }
                else
                {
                    if (i != 0)
                    {
                        //工时大于0的才记录,不能用worktime，几秒时就是0
                        decimal gs=Math.Round(worktime / 3600, 2);
                        if (gs > 0)
                        {
                            arg.gs = Math.Round(worktime / 3600, 2);
                            worktime = 0;
                            list.Add(arg);
                            TotalHours += gs;
                            num++;
                        }
                    }
                    //防止下一天或一个人的再次
                    beginTime = DateTime.MinValue;
                    endTime = DateTime.MinValue;
                    bool isEnter = Convert.ToBoolean(dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }

                    sfzh_b = sfzh_1;
                    dksj_b = dksj_1;
                    WorkTime w = new WorkTime();
                    w.xh = num;
                    w.xm = dr["xm"].ToString();
                    w.gh = dr["gh"].ToString();
                    w.sfzh = dr["sfzh"].ToString();
                    w.bz = dr["bzmc"].ToString();
                    w.bzmc = dr["bzmc"].ToString();
                    w.gz = dr["gz"].ToString();
                    w.rq = Convert.ToDateTime(dksj_b);
                    arg = w;
                }
            }
            if (!string.IsNullOrEmpty(arg.sfzh))
            {
                arg.gs = Math.Round(worktime / 3600, 2);
                list.Add(arg);
            }
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = list;
            return list;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            bind();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {

            try
            {
                List<WorkTime> list = bind();
                if (list.Count == 0)
                {
                    MessageBox.Show("没有数据！"); return;
                }

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //设置文件类型   
                saveFileDialog1.Filter = " xls files(*.xls)|*.xls";
                //设置默认文件类型显示顺序   
                saveFileDialog1.FilterIndex = 2;
                //保存对话框是否记忆上次打开的目录   
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.FileName = "员工工时统计";
                //点了保存按钮进入   
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {

                    int count = list.Count;
                    string team = this.cboTeam.Text.ToString().Trim();
                    decimal totalHours = TotalHours;
                    DateTime dt1 = picBegin.Value;
                    DateTime dt2 = picEnd.Value;
                    string title = dt1.ToString("yyyy年M月d日") + "---" + dt2.ToString("yyyy年M月d日");
                    string fileName = saveFileDialog1.FileName;
                    string[] oldCols = new string[] { "xh","xm","sfzh","gh","bz","gz","rq","gs" };
                    string[] newCols = new string[] { "序号","姓名","身份证","工号","班组","工种","日期","工时(小时)" };
                    DataTable dt = ToDataSet(list).Tables[0];
                    ExcelHelper.ExportByWorkTime(dt, "员工工时统计", fileName, "Sheet1", oldCols, newCols, title, count.ToString(), totalHours.ToString(), team);
                    MessageBox.Show("导出文件成功！"); return;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message); return;
                MessageBox.Show("导出文件故障！"); return;
            }
        }

        public static DataSet ToDataSet(IList p_List)
        {
            DataSet result = new DataSet();
            DataTable _DataTable = new DataTable();
            if (p_List.Count > 0)
            {
                PropertyInfo[] propertys = p_List[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    _DataTable.Columns.Add(pi.Name, pi.PropertyType);//columnName Type
                }

                for (int i = 0; i < p_List.Count; i++)
                {
                    ArrayList tempList = new ArrayList();    //一行数据的数组
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(p_List[i], null);//p_List[i]是集合中的某一个对象，GetValue 返回其属性值
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true); //LoadDataRow 查找和更新特定行。 如果找不到任何匹配行，则使用给定值创建新行
                }
            }
            result.Tables.Add(_DataTable);
            return result;
        }

        /// <summary>
        /// 调用窗口
        /// </summary>
        /// <param name="title">窗体名称</param>
        /// <param name="xmmc">项目名称</param>
        /// <returns></returns>
        public bool ShowExtension(string title, string xmmc)
        {
            try
            {
                WorkHoursForm whf = new WorkHoursForm();
                //whf.Text = title;
                //whf.Tag = xmmc;
                whf.ShowDialog();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载失败！");
                return false;
            }
        }
    }
    public class WorkTime
    {
        public int xh { get; set; }
        public string xm { get; set; }
        public string sfzh { get; set; }
        public string gh { get; set; }
        public string bz { get; set; }
        public string gz { get; set; }
        public string xb { get; set; }
        public string bankName { get; set; }
        public string bankCard { get; set; }
        public DateTime rq { get; set; }
        public decimal gs { get; set; }
        public decimal dygs { get; set; }
        public string bzmc { get; set; }
    }
     
}
